<template>
  <basic-container>
    <el-descriptions :title="data.name" border :column="1">
      <el-descriptions-item label="考试要求：">
        <div v-html="data.note" class="text-left"></div>
      </el-descriptions-item>
      <el-descriptions-item label="题型分布：">
        <div class="flex-box">
          <div v-html="data.questionRule"></div>
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="考试时长：">
        <div class="text-left">{{ data.maxTime }}分钟</div>
      </el-descriptions-item>
      <el-descriptions-item label="及格分数：">
        <div class="text-left">{{ data.passPercent }}%</div>
      </el-descriptions-item>
    </el-descriptions>
    <div class="mt10 flex flex-center">
      <el-button type="primary" v-if="state == 2" @click="startExams">开始考试</el-button>
      <el-button type="primary" v-else-if="state == 3" @click="startExams">继续考试</el-button>
      <el-button type="info" v-else @click="showExams">考试结束</el-button>
    </div>
    <el-dialog
      v-model="visible"
      center
      :fullscreen="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="wrap flex h100">
        <el-row class="flex1 h100 mt5 mb-5">
          <el-col :span="5" class="h100">
            <basic-container class="h100">
              <el-descriptions border :column="1" direction="vertical" class="h100">
                <el-descriptions-item label="序号" class="h100">
                  <div class="flex flex-wrap h100">
                    <el-button
                      v-for="(_item, index) in data.examQuestionList"
                      :key="index"
                      class="btnIndex"
                      :type="index == activeIndex ? 'primary' : 'info'"
                      :plain="index == activeIndex ? false : true"
                      @click="setActive(index)"
                    >
                      {{ index + 1 }}
                    </el-button>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </basic-container>
          </el-col>
          <el-col :span="14" class="h100">
            <basic-container class="h100">
              <el-descriptions border :column="1" direction="vertical" class="h100">
                <el-descriptions-item label="内容" class="h100">
                  <div style="line-height: 1.8">
                    <div class="text-left">
                      <h3>
                        <span>分类：{{ levelTypes }} </span>
                        <span class="ml50">题型：{{ questionTypes }}</span>
                        <span class="ml50">分数：{{ currentQuestion.score }}</span>
                      </h3>
                    </div>

                    <div class="text-left">
                      <h3>题干：</h3>
                    </div>
                    <div class="text-left" v-if="currentQuestion.type == '21'">
                      <div class="q-title" v-html="currentQuestion.title" />
                      <h3>选项：</h3>
                      <div class="q-content">
                        <el-radio-group v-model="answer[activeIndex]" @change="onchange">
                          <el-radio
                            :label="item.prefix"
                            v-for="item in currentQuestion.content"
                            :key="item.prefix"
                          >
                            <span class="mr10">{{ item.prefix }}.</span>
                            <span v-html="item.content" class="q-item-content"></span>
                          </el-radio>
                        </el-radio-group>
                      </div>
                    </div>
                    <div class="text-left" v-else-if="currentQuestion.type == '22'">
                      <div class="q-title" v-html="currentQuestion.title" />
                      <h3>选项：</h3>
                      <div class="q-content">
                        <el-checkbox-group v-model="answer[activeIndex]" @change="onchange">
                          <el-checkbox
                            :label="item.prefix"
                            v-for="item in currentQuestion.content"
                            :key="item.prefix"
                          >
                            <span class="mr10">{{ item.prefix }}.</span>
                            <span v-html="item.content" class="q-item-content"></span>
                          </el-checkbox>
                        </el-checkbox-group>
                      </div>
                    </div>
                    <div class="text-left" v-else-if="currentQuestion.type == '11'">
                      <div class="q-title" v-html="currentQuestion.title" />
                      <h3>选项：</h3>
                      <div class="q-content">
                        <el-radio-group v-model="answer[activeIndex]" @change="onchange">
                          <el-radio
                            :label="item.content"
                            v-for="item in currentQuestion.content"
                            :key="item.content"
                          >
                            <span v-html="item.content" class="q-item-content"></span>
                          </el-radio>
                        </el-radio-group>
                      </div>
                    </div>
                    <div class="text-left" v-else-if="currentQuestion.type == '31'">
                      <div class="q-title" v-html="currentQuestion.title" />
                    </div>
                    <div class="text-left" v-else-if="currentQuestion.type == '32'">
                      <div class="q-title" v-html="currentQuestion.title" />
                    </div>

                    <div class="text-left">
                      <div v-if="currentQuestion.type == '32' || currentQuestion.type == '31'">
                        <h3>答案：</h3>
                        <el-input type="textarea" v-model="answer[activeIndex]" @blur="onchange" />
                      </div>
                    </div>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </basic-container>
          </el-col>
          <el-col :span="5" class="h100">
            <basic-container class="h100">
              <el-descriptions border :column="1" direction="vertical" class="h100">
                <el-descriptions-item label="其他" class="h100">
                  <div class="mtb10">
                    <span>总时长：</span>
                    <span>{{ data.maxTime }}分钟 </span>
                  </div>
                  <div class="mtb10">
                    <span>总分数：</span>
                    <span>{{ data.totalScore }}分 </span>
                  </div>
                  <div class="mtb10">
                    <span>总分数：</span>
                    <span>{{ data.totalScore }}分 </span>
                  </div>
                  <div class="text-center border">
                    <p>剩余时间</p>
                    <p class="lastTime">{{ lastTime }}</p>
                  </div>
                  <div class="mtb10 text-center">
                    <el-button type="primary" @click="submit">提交试卷</el-button>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </basic-container>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <el-dialog v-model="isSubmit">
      <div>
        <h2 class="text-center">{{ data.name }}</h2>
        <div>
          <div class="flex border-t">
            <h3 class="mr10">客观题</h3>
            <el-card>
              <div class="item">
                <div class="mr10">【单选题】</div>
                <div>
                  <span
                    v-for="(item, index) in answerRes.single"
                    :key="index"
                    :class="setClass(item)"
                    class="mr10"
                  >
                    <el-tag @click="showQuestion(item.index)" :type="setClass(item)">
                      {{ item.index }}
                    </el-tag>
                    {{ item.answer }}
                  </span>
                </div>
              </div>
              <div class="item">
                <div class="mr10">【多选题】</div>
                <div>
                  <span
                    v-for="(item, index) in answerRes.mul"
                    :key="index"
                    :class="setClass(item)"
                    class="mr10"
                  >
                    <el-tag @click="showQuestion(item.index)" :type="setClass(item)">
                      {{ item.index }}
                    </el-tag>
                    {{ item.answer }}
                  </span>
                </div>
              </div>
              <div class="item">
                <div class="mr10">【判断题】</div>
                <div>
                  <span
                    v-for="(item, index) in answerRes.true"
                    :key="index"
                    :class="setClass(item)"
                    class="mr10"
                  >
                    <el-tag @click="showQuestion(item.index)" :type="setClass(item)">
                      {{ item.index }}
                    </el-tag>
                    {{ item.answer }}
                  </span>
                </div>
              </div>
            </el-card>
          </div>
          <div class="flex border-t">
            <h3 class="mr10">主观题</h3>
            <el-card>
              <div class="item">
                <div class="mr10">【简答题】</div>
                <div>
                  <span v-for="(item, index) in answerRes.short" :key="index" class="mr10">
                    <el-tag @click="showQuestion(item.index)" :type="setClass(item)">
                      {{ item.index }}
                    </el-tag>
                    {{ item.answer }}
                  </span>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        <div class="flex flex-center border-t pt15">
          <el-button type="primary" class="mr10" @click="onconfirmSubmit">确认提交</el-button>
          <el-button type="info" @click="isSubmit = false">返回修改</el-button>
        </div>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { startExam, examUserAnswer, examInstanceSubmit } from '@/api/position/positionInstance';
import { serverTime } from '@/api/position/courseware';

export default {
  props: {
    title: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: '',
    },
    examRule: {
      type: String,
      default: '',
    },
    state: {
      type: Number,
      default: 2,
    },
  },
  data() {
    return {
      data: {},
      visible: false,
      activeIndex: 0,
      currentQuestion: {},
      answer: [],
      timer: null,
      isSubmit: false,
      answerRes: {
        gap: [],
        mul: [],
        short: [],
        single: [],
        true: [],
      },
      lastTime: '',
    };
  },
  mounted() {
    this.exam();
    if (this.state == 3) {
      this.startExams();
    }
    console.log(this.title, this.id, this.state, this.examRule);
  },
  computed: {
    levelTypes() {
      const level = this.website.knowledgeLevelLists.find(
        type => type.value == this.currentQuestion.level
      );
      if (level) {
        return level.label;
      } else {
        return '';
      }
    },
    questionTypes() {
      const level = this.website.questionType.find(type => type.value == this.currentQuestion.type);
      if (level) {
        return level.label;
      } else {
        return '';
      }
    },
  },
  methods: {
    async exam() {
      let data = this.examRule;
      this.data = data;
      if (data.note) {
        this.data.note = data.note.replaceAll('\n', '<br />');
      }
      if (data.quantityList) {
        this.data.questionRule = data.quantityList
          .map(item => {
            return `<div style="margin-right:20px;">${item.name}:<span style="margin-left: 10px; color:red;">${item.quantity}</span></div>`;
          })
          .join('');
      }
      console.log(3, this.data.questionRule);
    },
    setActive(index) {
      this.activeIndex = index;
      this.currentQuestion = this.data.examQuestionList[index];
      this.currentQuestion.title = decodeURIComponent(this.currentQuestion.title);
      if (typeof this.currentQuestion.content == 'string') {
        const content = JSON.parse(decodeURIComponent(this.currentQuestion.content));
        this.currentQuestion.content = [];
        for (let key in content) {
          this.currentQuestion.content.push({
            prefix: key,
            content: content[key],
          });
        }
      }
      console.log('currentQuestion', this.currentQuestion);
    },
    async startExams() {
      this.visible = true;
      const res = await startExam(this.id, this.state == 2);
      console.log('startExams', res);
      this.data = res.data.data;
      this.answer = this.data.examQuestionList.map(item => {
        if (item.type == 22) {
          return item.userAnswerVO.userAnswer.split(',');
        } else {
          return item.userAnswerVO.userAnswer;
        }
      });
      this.setActive(0);
      this.setTime();
    },
    async setTime() {
      const res = await serverTime();
      let sTime = new Date(res.data.data).getTime() / 1000;
      let bTime = new Date(this.data.beginTime).getTime() / 1000;
      let dTime = this.data.maxTime * 60 - (sTime - bTime);
      this.timer = setInterval(() => {
        let s = dTime % 60;
        let m = parseInt(dTime / 60);
        this.lastTime = `${m}分钟${s}秒钟`;
        dTime--;
        if (dTime == 0) {
          this.onconfirmSubmit();
        }
      }, 1000);
    },
    showExams() {
      // this.visible = true;
    },
    async submit() {
      console.log('this.data.examQuestionList', this.data.examQuestionList);
      this.answerRes = {
        gap: [],
        mul: [],
        short: [],
        single: [],
        true: [],
      };
      this.data.examQuestionList.forEach((list, index) => {
        let obj = {
          index: index + 1,
          answer: list.userAnswerVO.userAnswer,
        };
        if (list.type == 21) {
          this.answerRes.single.push(obj);
        } else if (list.type == 22) {
          this.answerRes.mul.push(obj);
        } else if (list.type == 11) {
          this.answerRes.true.push(obj);
        } else if (list.type == 31) {
          this.answerRes.gap.push(obj);
        } else if (list.type == 32) {
          this.answerRes.short.push(obj);
        }
      });
      this.isSubmit = true;
    },
    async onconfirmSubmit() {
      await examInstanceSubmit(this.data.id)
      this.visible = false;
      this.isSubmit = false;
      this.$emit('close');
      clearInterval(this.timer);
    },
    onchange() {
      if (this.currentQuestion.type == 22) {
        this.currentQuestion.userAnswerVO.userAnswer = this.answer[this.activeIndex]
          .filter(item => item)
          .join(',');
      } else {
        console.log(this.answer, this.activeIndex);
        this.currentQuestion.userAnswerVO.userAnswer = this.answer[this.activeIndex];
      }
      examUserAnswer(this.currentQuestion.userAnswerVO);
    },
    setClass(item) {
      if (!item.answer) {
        return 'danger';
      } else if (item.answer == '免考') {
        return 'success';
      } else {
        return '';
      }
    },
    closeExam() {
      console.log(3333);
    },
    showQuestion(index) {
      this.isSubmit = false;
      this.setActive(index - 1);
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-descriptions__title) {
  flex: 1;
  text-align: center !important;
  white-space: nowrap;
}

:deep(.el-descriptions__label) {
  text-align: center !important;
  white-space: nowrap;
  width: 200px;
}

.wrap {
  margin: -40px -10px;
  width: calc(100vw - 30px);
  height: calc(100vh - 30px);
  overflow: auto;
  background: #eee;
  border-radius: 10px;
  box-shadow: 0 0 10px #999;
  padding: 10px 7px;
  box-sizing: border-box;
}

:deep(.el-icon) {
  z-index: 1000;
}

.btnIndex {
  width: 39px;
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 10px !important;
  box-sizing: border-box;
  &:nth-child(5n) {
    margin-right: 0 !important;
  }
}

.border {
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  margin-top: 20px;
  margin-bottom: 20px;
}

.lastTime {
  font-size: 20px;
  color: red;
}

:deep(.el-card) {
  height: 100% !important;
}

.flex {
  display: flex;
}

.flex-box > div {
  display: flex;
}

:deep(.el-checkbox-group),
:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

:deep(.el-checkbox__label),
:deep(.el-radio__label) {
  display: flex;
}
:deep(.el-radio),
:deep(.el-checkbox) {
  height: auto;
  align-items: center;
  margin-bottom: 10px;
}

:deep(.el-card) {
  overflow: auto;
}
.text-left {
  text-align: left;
}
.item {
  margin-bottom: 10px;
}

.green {
  color: green;
}
.red {
  color: red;
}
.border-t {
  border-top: 1px solid #ccc;
}
.pt15 {
  padding-top: 15px;
}
.tag {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #08d4ee;
  margin-right: 5px !important;
  color: #333;
  text-align: center;
  line-height: 20px;
}
.el-tag {
  cursor: pointer;
}
</style>
<style>
.q-item-content p {
  margin: 0 !important;
}
</style>
